package service;

import dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import pojo.UserInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * 查询用户信息提交给Security
 * 实现UserDetailsService接口
 * */
public class UserService implements UserDetailsService {

    @Autowired
    UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //模拟从数据库查询数据
        UserInfo userInfo = userDao.findByUsername(username);

        //初始角色和权限的集合(GrantedAuthority：角色和权限共用接口),并添加角色和权限
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

        //添加1个角色(角色必须带"ROLE_")
        GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_ADMIN");
        authorities.add(authority);

        //处理完数据要给Security的对象
        UserDetails userDetails = new User(username,userInfo.getPassWord(),authorities);

        return userDetails;
    }

    /**
     * 测试BCryptPasswordEncoder加密
     */
    public  static void main(String[] args){
        BCryptPasswordEncoder bpe = new BCryptPasswordEncoder();
        //加密
//        String encode = bpe.encode("1234");
//        System.out.println(encode);
        // 密码匹配
        // 明文
        // 密文
        boolean matches = bpe.matches("1234", "$2a$10$FrHT591r/apRs3fkRq9RgOG./tA1gUgh4rBWNph3ncSXU81vr.D/C");
        System.out.println(matches);

    }


}
